# _*_ coding:utf-8 _*_
"""
__Author__    :  Icy
__Date__      :  2018/5/4
__File__      :  model.py
__Desc__      :
"""
import datetime

import pymongo
from cfg.dbcfg import HOST, PORT, DATABASE


class DB(object):
	conn = pymongo.MongoClient(host=HOST, port=PORT)
	db = conn[DATABASE]
	message = db['message']
	tuser = db['tuser']
	chats = db['chats']

	@classmethod
	def create_message(cls, from_user, username, message):
		return cls.message.insert({'from_user': from_user,
		                    'name': username,
		                    'timestamp': datetime.datetime.now(),
		                    'message': message})
	@classmethod
	def find_message(cls,**kwargs):
		if not kwargs:
			return False
		return cls.message.find_one(kwargs)



	@classmethod
	def create_user(cls, **user):
		cls.tuser.insert_one(user)

	@classmethod
	def check_user(cls, **kwargs):
		if not kwargs:
			return False
		Exists = False
		try:
			Exists = cls.tuser.find_one(kwargs)
		except:
			Exists = False
			pass
		finally:
			return Exists

	@classmethod
	def get_or_create_chat(cls, from_user, to_user, who, **kwargs):
		"""
		:param who: 用户名字
		:return:
		"""
		query = {
			"from":from_user,
			"to":to_user
		}
		result = cls.chats.find_one(query)
		if not result:
			result = cls.chats.insert_one({'from': from_user,
		                               'to': to_user,
		                               'who': who,
		                               'new': 0,
		                               'msgs': []})


	@classmethod
	def add_message_to_chat(cls, message, from_user, to_user):
		query = {
			'from': from_user.get("_id"),
			'to': to_user.get("_id")
		}
		cls.chats.find_one_and_update(query, update={
			'$push': {'msgs': message}
		})

	@classmethod
	def add_friend(cls, owner, user):
		try:
			cls.tuser.find_one_and_update({'userame': owner}, update={'$push': {
				'friends': user}})
		except Exception as e:
			return False
	@classmethod
	def get_firends(cls,user:dict):

		ur = cls.tuser.find_one({"username":user.get('username')})
		friendss = list()
		friendids = ur.get('friends')

		for idd in friendids:
			t = cls.tuser.find_one({"_id":idd})
			friendss.append(t)
		return friendss


if __name__ == "__main__":
	pass
